package com.molyfun.parents.activity.common.listactivity.factory;

import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.listactivity.AbstractListFactory;
import com.molyfun.parents.activity.common.listactivity.IResponse;
import com.molyfun.parents.activity.common.listactivity.viewholder.CourseViewHolder;
import com.molyfun.parents.activity.course.downloadObserver.CourseDownloadProgressCenter;
import com.molyfun.parents.dao.entity.CourseDownloadTask;
import com.molyfun.parents.dao.gen.CourseDownloadTaskDao;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.CourseListResponse;
import com.molyfun.parents.service.filedownload.CourseDownLoadUtils;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.NetWorkUtil;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:10/31/16.
 *
 * 我的赞列表
 */
public class DownLoadFactory extends AbstractListFactory<CourseListResponse.CourseBean> {

    private CourseDownloadTaskDao courseDownloadTaskDao;

    public DownLoadFactory(){
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        courseDownloadTaskDao = daoSession.getCourseDownloadTaskDao();
    }

    @Override
    public int getTitle() {
        return R.string.activity_title_mine_download;
    }

    @Override
    public void getDataList(int pageNum,final IResponse responseCallback) {

        if(NetWorkUtil.isNetworkAvailable(MFPApplication.getInstance())){
            Call<CourseListResponse> call = MFPApplication.getInstance().getRestClient().getDownLoadList(pageNum, RestClient.DEFAULT_PAGE_SIZE);
            call.enqueue(new Callback<CourseListResponse>() {
                @Override
                public void onResponse(Call<CourseListResponse> call, Response<CourseListResponse> response) {
                    if (response.body() != null && response.body().getData() != null && response.body().getData().getRecords() != null) {
                        responseCallback.onResponse(response.body().getData().getRecords());
                    }
                }

                @Override
                public void onFailure(Call<CourseListResponse> call, Throwable t) {
                }
            });
        }else{
            if(pageNum == RestClient.DEFAULT_PAGE){
                List<CourseDownloadTask> courseDownloadTasks = courseDownloadTaskDao.queryBuilder()
                        .build().list();
                List<CourseListResponse.CourseBean> courseBeans = new ArrayList<>();
                if(courseDownloadTasks != null ){
                    for(CourseDownloadTask courseDownloadTask : courseDownloadTasks){
                        CourseListResponse.CourseBean courseBean = GsonUtil.fromJson(courseDownloadTask.getJsonStr(), CourseListResponse.CourseBean.class);
                        courseBeans.add(courseBean);
                    }
                }
                responseCallback.onResponse(courseBeans);
            }
        }
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(ViewGroup parent, int viewType) {
        return new CourseViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_course_cell, parent, false));
    }

    @Override
    public void bindViewHolder(final Context context, final CourseListResponse.CourseBean courseBean, RecyclerView.ViewHolder holder, final int position, FragmentManager fragmentManager, int totalSize) {
        CourseViewHolder courseViewHolder = (CourseViewHolder)holder;
        courseViewHolder.mCourseView.initData(courseBean, fragmentManager);
        courseViewHolder.mCourseView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if(mOnListOperationCallback != null){
                    mOnListOperationCallback.onLongClick(courseBean.getDkey() + "_" + courseBean.getRelid(), position);
                }
                return false;
            }
        });
    }

    @Override
    public void deleteData(final String id,final int position) {
        //[0] courseId,[1]relid
        final String[] ids = id.split("_");
        if(NetWorkUtil.isNetworkAvailable(MFPApplication.getInstance()) && !TextUtils.isEmpty(ids[1])){
            Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().delCourseDownload(ids[1]);
            call.enqueue(new Callback<BaseResponse>() {
                @Override
                public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {

                    CourseDownloadProgressCenter.getInstance().removeCourseDownloadState(ids[0]);

                    CourseDownloadTask courseDownloadTask = courseDownloadTaskDao.queryBuilder().where(CourseDownloadTaskDao.Properties.DownloadKeyId.eq(ids[0])).build().unique();
                    if (courseDownloadTask != null) {
                        courseDownloadTaskDao.delete(courseDownloadTask);
                    }
                    CourseDownLoadUtils.delDownLoadCourseMediaList(ids[0]);

                    if (mOnListOperationCallback != null) {
                        mOnListOperationCallback.onDataDelete(position);
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse> call, Throwable t) {

                }
            });
        }else{
            if(!TextUtils.isEmpty(ids[0])){
                CourseDownloadProgressCenter.getInstance().removeCourseDownloadState(ids[0]);
                CourseDownloadTask courseDownloadTask = courseDownloadTaskDao.queryBuilder().where(CourseDownloadTaskDao.Properties.DownloadKeyId.eq(ids[0])).build().unique();
                if (courseDownloadTask != null) {
                    courseDownloadTaskDao.delete(courseDownloadTask);
                }
                CourseDownLoadUtils.delDownLoadCourseMediaList(ids[0]);
                if (mOnListOperationCallback != null) {
                    mOnListOperationCallback.onDataDelete(position);
                }
            }

        }

    }
}
